#! /usr/bin/env python
# coding=utf-8

import struct
import json


class MapsProtocol:
    _headerlen = 4
    _pack_key = '!I{}s'
    _unpack_key = "!{}s"
    _header_key = '!I'

    def __init__(self):
        """
        #+-------------+-------------------+
        #| length      | message           |
        #+-------------+-------------------+
        #
        # https://docs.python.org/3/library/struct.html#byte-order-size-and-alignment
        # +--------+--------------+-------------+----------------+
        # | format | C type       | python type | standard  size |
        # +------------------------------------------------------+
        # | I | unsigned int      | integer     | 4              |
        # +------------------------------------------------------+
        # | s | char[]            | bytes       |                |
        # +--------+--------------+-------------+----------------+
        """
        # self._pack_key = '!I{}s'
        # self._unpack_key = "!{}s"
        # self._header_key = '!I'

    @classmethod
    def get_header(cls, data):
        """
        :4字节read_bytes 读取头部信息  解析头部信息获取头部长度
        :param data
        :return length
        """
        length = struct.unpack(cls._header_key, data)
        return length[0]

    @classmethod
    def get_content_json(cls, length, data):
        """
        由header解析获取body的长度读取 data
        :return data
        """
        ret = struct.unpack(cls._unpack_key.format(length), data)
        return json.loads(ret[0].decode())

    @classmethod
    def inpack(cls, data):
        """
        :用来和u3d协议的封装包函数  消息(4字节) = 消息体长度 + 消息体
        :return:
        """
        data = json.dumps(data)
        length = len(data.encode(encoding="utf-8"))
        ret = struct.pack(cls._pack_key.format(length), length, data.encode())
        return ret


mapsprotocol = MapsProtocol()
